package system;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Date;

import db.BaseDBProxy;

public class BookProxy extends BaseDBProxy<Book> {
	private static final String[] sColumnNames = {
		"name", "isbn", "author", "press", "description", "catagory",
		"publish_date", "price", "count", "id"
	};
	private String sTableName;

	public BookProxy() {
		this("books");
	}
	
	public BookProxy(String pTableName) {
		sTableName = pTableName;
	}
	
	@Override
	protected String[] getTableColumnNames() {
		return sColumnNames;
	}
	
	@SuppressWarnings("deprecation")
	@Override
	protected String[] getRightValues(Book pItem) {
		String[] values = new String[sColumnNames.length];
		values[0] = "'" + pItem.getName() + "'";
		values[1] = "'" + pItem.getIsbn() + "'";
		values[2] = "'" + pItem.getAuthor() + "'";
		values[3] = "'" + pItem.getPress() + "'";
		values[4] = "'" + pItem.getDescription() + "'";
		values[5] = "'" + pItem.getCatagory() + "'";
		
		Date date = pItem.getPublish_date();
		if (date == null) {
			values[6] = null;
		} else {
			int y = date.getYear() + 1900;
			int m = date.getMonth() + 1;
			int d = date.getDate();
			values[6] = String.format("%04d%02d%02d", y, m, d);
		}
		
		values[7] = String.valueOf(pItem.getPrice());
		values[8] = String.valueOf(pItem.getCount());
		values[9] = String.valueOf(pItem.getId());
		return values;
	}

	@Override
	protected Book inflate(ResultSet pResultSet) throws SQLException {
		Book book = new Book();
		book.name = pResultSet.getString(sColumnNames[0]);
		book.isbn = pResultSet.getString(sColumnNames[1]);
		book.author = pResultSet.getString(sColumnNames[2]);
		book.press = pResultSet.getString(sColumnNames[3]);
		book.description = pResultSet.getString(sColumnNames[4]);
		book.catagory = pResultSet.getString(sColumnNames[5]);
		book.publish_date = pResultSet.getDate(sColumnNames[6]);
		book.price = pResultSet.getDouble(sColumnNames[7]);
		book.count = pResultSet.getInt(sColumnNames[8]);
		book.id = pResultSet.getLong(sColumnNames[9]);
		
		return book;
	}

	@Override
	protected String getTableName() {
		return sTableName;
	}
	
}
